<?php
ini_set('display_errors',1);            //错误信息
ini_set('display_startup_errors',1);    //php启动错误信息
error_reporting(-1);                    //打印出所有的 错误信息
ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); //将出错信息输出到一个文本文件
/*
 * object(stdClass)#3 (2) { ["alipay_system_oauth_token_response"]=> object(stdClass)#4 (6) { ["access_token"]=> string(40) "composeBa59bdf8e223d4faa82ef48ce67f75X62" ["alipay_user_id"]=> string(32) "20880047227871702781910743017362" ["expires_in"]=> int(3600) ["re_expires_in"]=> int(3600) ["refresh_token"]=> string(40) "composeB03d46fe19a264814b0715bba01510X62" ["user_id"]=> string(16) "2088012954780622" } ["sign"]=> string(344) "X+TrXJh8GOGIS7PbkyMaucb/HYVC6w+DY+NihjNtwmhoLB3jAe8rXFQJ3LQZ5HEUQFGpK8D9hAD/CuHunq8jCdZEGApsj+tQNOk7caLF2kM+V/Qw0orxdV8L1fq76si4/szG9aXUVvCvurWaICLK9W2ouSnJ2PVQpmWusAOkxEZMyq3ucRjEgcGBNsqEifCtDfDGsvcxWtz64EMoZR6HFhT3gQgqMH0fQ9vYNMdaUcAQ14Gyk3t60Qd4HZTpHjio1oLde2c8EyrkSsvh/q3OsxjOqvES2MDVs5wxLGLyY/+vjhd3d0WP7jotOVc1EwP5/QU6Juv0j2VIoCCS33bwEA==" } string(40) "composeBa59bdf8e223d4faa82ef48ce67f75X62" string(32) "20880047227871702781910743017362" string(16) "2088012954780622"
 *8U3eW2z-TXKUDlIfb5qJfAAAACMAAQE
 * logo Ype-hZpSTNKCKoZTp1CR8QAAACMAAQED
 * */
include '../AopClient.php';
include '../SignData.php';
include('../AlipayMobilePublicMultiMediaClient.php');
include('../request/AlipayMarketingCardQueryRequest.php');
include('../request/AlipayMarketingCardFormtemplateSetRequest.php');
include('../request/AlipayMarketingCardTemplateQueryRequest.php');
include('../request/AlipayMarketingCardTemplateCreateRequest.php');
include('../request/AlipayMarketingCardActivateurlApplyRequest.php');
include('../request/AlipaySystemOauthTokenRequest.php');
include('../request/AlipayMarketingCardOpenRequest.php');
include('../request/AlipayOfflineMaterialImageUploadRequest.php');
include('../request/AlipayOpenAuthTokenAppRequest.php');

function conventjson($data){
    return json_encode(json_encode($data,JSON_UNESCAPED_UNICODE));
}
class Card{
    private	$format = 'json';
    private	$aop;
    function __construct(){
        header("Content-type:text/html;charset=utf-8");
        $this->aop = new \AopClient ();
        $this->aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $this->aop->appId = '2018011901971979';
        $this->aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEA0Hx+9wgN4ParmGATI2ykd4HnwqV2yhUKfPXCLWMXCxyT83akGBPt/svUBeYCd5ZhVMMebYQ6ZfJVtfCCF6aQAQQvZujgcCdWm4nO6W1w7ryIhuwvT1ocsBKBGl3g+9YfvHWfPx2otIpvL5xPBYz3+0bk0Ge5EuVT4xjNsfIfNVMhOCddtX0VOfNFE7gzu6uVsEatFXLcwq2qCTVrx4SWjLCpYVmTdtoFAgJqrSvuXHDccAj7lA44vy1xJRpfzhddE+uQ2G+wcoK6Z/CW6RDpJ1zLhfcSRfvxO+gWLk72UI7W6U3LAa5ULc3moUqFbOfjE73fjQIynCIoAT1AdRq7WwIDAQABAoIBAQCBiQid1dxBrSFakD7z4JmjQwxLbOEMl9wnXc6iwpFbrwrh1xIHf8J8cAoxDAL2aHHa50xtgR2Dn/jPDTrXFP8eEoqdJw3jwR1XkF0FvaDQREWThwWyCOwQHb8nMbMK5bRcNLyXy4a5fdWtQDH84eRltFuQfRGJgwEG9a8/446uYvP5ZuW5DDyGWKJ6XbQbaYfsZ7ID5ek4/I9xZYUeMRe8xyeGB2Es4Gq0Cz0q2uGicUOB2d28nPNnK9gzSrJIo3EZu9nJg+T83YSMeO5f0T3YW1Id2nvL4Ksbp6Gx23jLbGCIKcDKzJLgt/yJBEokYHaTzU1VN98yBbTor27XSik5AoGBAOvQ4LCNpOwJLVpX+JC/7yFz24XfnYy8gqwN4fVdOPV9tnUXGyfgxiAPsO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ewOr7FCRn3mBu5PYDNkrTQiNiECOXj1bO6/O6rFZ8lqvOV7Tb0hk8iobT19dMhlUCR4jE1jWGTTHVHZh1OrlV1zHjkHcRdLihCyMM3WQWz5pOvDuBhtl9JVA/MaeeFEgHTxde3QIDAQAB';
        $this->aop->apiVersion = '1.0';
        $this->aop->signType = 'RSA2';
        $this->aop->postCharset='utf-8';
        $this->aop->format='json';
    }
public function image_upload(){
    $request = new AlipayOfflineMaterialImageUploadRequest ();
    $request->setImageType("jpg");
    $request->setImageName("积分红包");
    $request->setImageContent("@"."./3.png");
    $result = $this->aop->execute ( $request);
    var_dump($result);
    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $resultCode = $result->$responseNode->code;
    if(!empty($resultCode)&&$resultCode == 10000){
        echo "成功";
    } else {
        echo "失败";
    }
}
public function createTemplate($data){
            $request = new \AlipayMarketingCardTemplateCreateRequest ();
            $request->setBizContent($data);
            $result = $this->aop->execute ( $request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            var_dump($result);
            if(!empty($resultCode)&&$resultCode == 10000){
                echo "成功";
            } else {
                echo "失败";
            }

  }
public function addMarketCardJson(){
        $json_data = array();
        $json_data['request_id'] = '20180122000000000780217000300777';
        $json_data['card_type'] = 'OUT_MEMBER_CARD';
        $json_data['biz_no_prefix'] = 'prex';
        $json_data['biz_no_suffix_len'] = '10';
        $json_data['write_off_type'] = 'qrcode'; #qrcode: 二维码 dqrcode: 动态二维码 barcode: 条码 dbarcode: 动态条码 text: 文本
        $json_data['template_style_info']['card_show_name'] = '星程会员卡';
        $json_data['template_style_info']['logo_id'] = 'Ype-hZpSTNKCKoZTp1CR8QAAACMAAQED';  # logo 上传后的ID 1M以内，格式bmp、png、jpeg、jpg、gif； 尺寸不小于500*500px的正方形； 请优先使用商家LOGO；
        $json_data['template_style_info']['color'] = 'rgb(255,0,0)'; #卡片背景色
    //2whz6v6kTUWDhhYZ0YVtjAAAACMAAQED
        $json_data['template_style_info']['background_id'] = 'qQVkzD44Q3iwSDiVvCeT-wAAACMAAQED'; # 上传背景图片返回的ID
        $json_data['template_style_info']['bg_color'] = 'rgb(255,0,0)'; # 背景色
        $json_data['column_info_list'] = array(
            array(
                "code"=> "BENEFIT_INFO",
            "more_info"=> [
        "title"=> "会员专享权益",
                "url"=> "http://test.xingchengfu.com/mid",
                "params"=> "{}"
            ],
            "title"=> "用户中心",
            "operate_type"=> "openWeb"
            )
        );

        $json_data['field_rule_list'] = array(
            array(
                'field_name' => 'Balance',  # Balance：金额 Point：整数 Level：任意字符串 OpenDate：开卡日期 ValidDate：过期日期
                'rule_name'  => 'ASSIGN_FROM_REQUEST', # 1.ASSIGN_FROM_REQUEST: 以rule_value为key值，表示该栏位的值从会员卡开卡接口中获取，会员卡开卡接口的card_info中获取对应参数值
                # 2、DATE_IN_FUTURE: 生成一个未来的日期（格式YYYY-MM-DD)，当选择DATE_IN_FUTURE的时候，field_name 必须是OpenDate或ValidDate， 值为(10m或10d 分别表示10个月或10天)
                # 3、CONST: 常量，会员卡开卡接口进行开卡的时候使用模板创建时候设置的值，即取rule_value的值
                'rule_value' => 'Balance'  # 根据rule_name，采取相应取值策略
                # 3.CONST：直接取rule_value作为卡属性值
                # 3.DATE_IN_FUTURE：10m或10d 分别表示10个月或10天
                # 1.ASSIGN_FROM_REQUEST：在开卡Reuqest请求中按rule_value取值，现在和field_name对应的为（OpenDate、ValidDate、Level、Point、Balance）
            ),
        );
        return $json_data;
        }
        //会员卡开卡表单模板配置
public function setformtemplate($template_id){
    $request = new \AlipayMarketingCardFormtemplateSetRequest ();
    $post_data=[
        'template_id'=>$template_id,
        'fields'=>[
           // 'required'=>['common_fields'=>['OPEN_FORM_FIELD_MOBILE']],

            'optional'=>['common_fields'=>['OPEN_FORM_FIELD_GENDER']]
        ]
    ];
    $request->setBizContent(json_encode($post_data,JSON_UNESCAPED_UNICODE));
    $result = $this->aop->execute ( $request);

    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $resultCode = $result->$responseNode->code;
    var_dump($result);
    if(!empty($resultCode)&&$resultCode == 10000){
        echo "成功";
    } else {
        echo "失败";
    }
}
public function activateurl_apply($template_id){
    $request = new \AlipayMarketingCardActivateurlApplyRequest ();
    $post_data=[

        'template_id'=>$template_id,
        'callback'=>'http://180.76.59.168/kabaotest/test/CardClass.php',
    ];
    $request->setBizContent(json_encode($post_data,JSON_UNESCAPED_UNICODE));
    $result = $this->aop->execute ( $request);
    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $resultCode = $result->$responseNode->code;
    var_dump( urldecode($result->alipay_marketing_card_activateurl_apply_response->apply_card_url));
    if(!empty($resultCode)&&$resultCode == 10000){
        echo "成功";
    } else {
        echo "失败";
    }
}
public function get_token($code){
    $request = new AlipaySystemOauthTokenRequest ();
    $request->setGrantType("authorization_code");
    $request->setCode($code);
    $result = $this->aop->execute ( $request);
    var_dump($result);
    return     [
 $result->alipay_system_oauth_token_response->access_token,                  $result->alipay_system_oauth_token_response->user_id
    ];
}
public function get_app_token($code){
    $request = new AlipayOpenAuthTokenAppRequest ();
    $post_data=[
        'grant_type'=>'authorization_code',
        'code'=>$code,
    ];
    $request->setBizContent(json_encode($post_data,JSON_UNESCAPED_UNICODE));
    $result = $this->aop->execute ( $request);
    var_dump($result);
    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $resultCode = $result->$responseNode->code;
    if(!empty($resultCode)&&$resultCode == 10000){
        echo "成功";
    } else {
        echo "失败";
    }
}
public function card_open($template_id,$token,$user_uni_id){
    $request = new \AlipayMarketingCardOpenRequest ();
    $post_data=[
        'out_serial_no'=>'E'.date('YmdHis').mt_rand(10000,99999),
        'card_template_id'=>$template_id,
        'card_user_info'=>[
            'user_uni_id'=>$user_uni_id,
            'user_uni_id_type'=>'UID',
        ],
        'card_ext_info'=>[
            'biz_card_no' => 'hha'.mt_rand(10000,99999),#支付宝业务卡号 说明： 1、开卡成功后返回该参数，需要保存留用； 2、开卡/更新/删卡/查询卡接口请求中不需要传该参数；
            'external_card_no'=>mt_rand(10000,99999), # 商户外部会员卡卡号 说明： 1、会员卡开卡接口，如果卡类型为外部会员卡，请求中则必须提供该参数； 2、更新、查询、删除等接口，请求中则不需要提供该参数值；
            'open_date' => date('Y-m-d H:i:s'),
            'valid_date' => date('2022-m-d H:i:s'),
//            'level' =>'VIP1',
            /*      'point' => '88',
                  'balance' => '128.88'*/
        ],
    ];
    $request->setBizContent(json_encode($post_data,JSON_UNESCAPED_UNICODE));

    $result = $this->aop->execute ( $request,$token  );
    var_dump($result);
    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $resultCode = $result->$responseNode->code;
    if(!empty($resultCode)&&$resultCode == 10000){
        echo "成功";
    } else {
        echo "失败";
    }
    return $result->$responseNode->card_info->biz_card_no;
    }
    public function Market_query($target_card_no){
        $request = new AlipayMarketingCardQueryRequest ();
        $post_data=[
            'target_card_no'=>$target_card_no,
            'target_card_no_type'=>'BIZ_CARD'
        ];
        $request->setBizContent(json_encode($post_data,JSON_UNESCAPED_UNICODE));
        $result = $this->aop->execute ( $request);
        var_dump($result);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            echo "成功";
        } else {
            echo "失败";
        }
        return $result->$responseNode->schema_url;
    }
    }

$ne=new Card();
//
//20180118000000000756307000300736
//20180121000000000766197000300734
//20180121000000000772229000300731
//20180122000000000770216000300735
//20180122000000000774265000300735
//20180122000000000773228000300730
//20180122000000000770224000300733
//20180122000000000777207000300731
//20180122000000000780217000300739
//20180122000000000775264000300730
//$templateid='20180122000000000768230000300738';
$templateid='20180122000000000780246000300732';
/*$templateid='20180122000000000768230000300738';
$ne->card_open($templateid,'composeBd62ed1e663f54722947f7b4e51a9cX49');exit;*/

//$ne->Market_query('prex0000006549');die;
//$ne->query();die;
//$ne->image_upload();die;
/*$post_data = json_encode($ne->addMarketCardJson(),JSON_UNESCAPED_UNICODE);
$ne->createTemplate(($post_data));die;*/
//$ne->setformtemplate($templateid);die;
//$ne->activateurl_apply($templateid);die;


//$code='b4f21c33a6b24a17b3127e4be9f4UC62';
//$token=$ne->get_token($code);
//$ne->card_open('20180122000000000773228000300730','composeBecb50a2073c14018a2c576cc16027X62');die;
//var_dump($_GET);die;
//$token=$ne->get_token('9da4218124cf4298ac5a6b5a876bQX62');
//var_dump($token);die;
//$ne->card_open($templateid,'composeB7cb8974f75664bcf8ea1a666b6c70D49');exit;
if (isset($_GET['auth_code'])){
    $code=$_GET['auth_code'];
    $get_token=$ne->get_token($code);
    $token=$get_token[0];
    $user_id=$get_token[1];
    $biz_card_no=$ne->card_open($templateid,$token,$user_id);
    $schema_url=$ne->Market_query($biz_card_no);
    header("location:".$schema_url);
    exit;
}

//$ne->image_upload();